import {Injectable} from "@angular/core";

declare var window:any;

@Injectable()
export class MapUtil {

  loadMapScript( callback:any ){
    if ( window.hasOwnProperty( 'BMap' ) ) {
      callback();
    } else {
      window.BMap_loadScriptTime = (new Date).getTime();
      window.BMap = window.BMap || {};
      window.BMap.apiLoad =  () => {
        delete window.BMap.apiLoad;
        callback();
      };
      this.loadMapLib('http://api.map.baidu.com/getscript?v=2.0&ak=SS4ym5KlDwbL1ld0GOu6Tiisa7A5mpXh&services=&t=20171014112628');
    }
  }

  loadMapLib( url:string ){
    let scriptElemArr: any = document.getElementsByTagName('script');
    let isExist: boolean = false;
    let scriptElemLength = scriptElemArr.length;
    for ( let i = 0; i < scriptElemLength; i++ ) {
      if(scriptElemArr[i].src == url){
        isExist = true;
        return;
      }
    }
    if ( !isExist ) {
      let s = document.createElement('script');
      s.src = url;
      document.body.appendChild(s);
    }
  }
}
